import asyncio
import json
import os
import sys
import urllib
from configparser import ConfigParser

import aioredis
from tornado import gen

sys.path.append(os.path.abspath('../'))
from baseHandler import init_logger, PayHandler, Application, http_result
from channel.channel_baiyin import BaiYing

class BaiYinNoti(PayHandler):
    def get(self):
        logger.info(self.request.arguments)
        self.write('SUCCESS')

    @gen.coroutine
    def post(self):
        logger.info(self.request.body)
        data = dict(urllib.parse.parse_qsl(self.request.body.decode('utf-8')))
        logger.info(data)
        if not baiyin.sign_verify(data):
            return self.write("FAILED")
        self.write("SUCCESS")
        self.finish()

        logger.info("通知|流水号%s|支付结果%s", data["orderNo"], data["respCode"])
        if data['respCode'] in ("0000", "00"):
            orderstate = '0'
        else:
            orderstate = "1"
        input_json = {
            "DEPTID": "800001",
            "OPERID": "9527",
            "FUNCTYPE": "NOTI",
            "FUNCCODE": "100201",
            "OPERPASS": "f15dbcb3154d37e4a183a350e4e8a15dde16a175",
            "REQINFO": {
                'OUTERORDERNO': data["orderNo"],
                "ORDERSTATE": orderstate,
                "OPMONEY": str(data["transAmt"]),
                "NOTIFYINFO": data['respDesc'],
            }
        }
        # 发送到核心程序
        result = yield from self.pay_core("PAY_ALIPAY_NOTIFY", input_json)
        logger.info(result)
        notifyurl = result.get("NOTIFIYURL", "")

        if notifyurl:
            merchantid = result.get("MERCHANTID")
            res = yield self.merchant_exit(merchantid=merchantid)
            for i in range(5):
                notify_data = {
                    "ordernumber": result["MERCHANTORDERNO"],
                    "respcode": result["ORDERSTATE"],
                    "merchantid": merchantid,
                    "amount": result["OPMONEY"],
                    "businesstime": result["RESPTIME"]
                }

                request_obj = self.niti_data(notify_data, result)
                rsp = yield http_result(notifyurl, request_obj, model='urlencode')
                logger.info(rsp.body)
                # content = rsp.body.upper()
                if rsp.code == 200 and rsp.body in (b'SUCCESS', b'success'):
                    logger.info("%s|%s收到下游成功应答|订单号%s", i, data["ordernumber"], result["MERCHANTORDERNO"])
                    noti = yield from self.pay_core("PAY_ALIPAY_NOTIFY_RES", {
                        "REQINFO": {"MERCHANTID": merchantid, "MERCHANTORDERNO": result["MERCHANTORDERNO"]}})
                    logger.debug(noti)
                    break
                else:
                    logger.info("%s|%s未收到下游成功应答|订单号%s", i, data["ordernumber"], result["MERCHANTORDERNO"])
                    yield from asyncio.sleep(10 * (i + 1))


if __name__ == "__main__":
    application = Application([
        (r"/noti/baiyin", BaiYinNoti),
    ], debug=True)

    cfg = ConfigParser()
    cfg.read('/home/pyapp/slsh/config/baiyin.ini')

    # init logger
    port = cfg.getint('server', 'noti_port')
    log_path = cfg.get('log', 'log_path')
    logger = init_logger("baiyin_noti", log_path, screen=True)

    application.listen(port, address='127.0.0.1')
    key = cfg.get('server', 'key')
    mchid = cfg.get('server', 'mchid')
    baiyin = BaiYing(mchid, key)
    application.baiyin = baiyin

    loop = asyncio.get_event_loop()
    application.init_with_loop(loop)
    logger.info("baiyin noti staring")
    loop.run_forever()
